package com.ld.poetry.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ld.poetry.entity.ResourceConfig;
import com.ld.poetry.service.FileUploadService;
import com.ld.poetry.utils.CommonConst;
import com.ld.poetry.utils.FileUploadUtils;
import com.ld.poetry.utils.PoetryUtil;
import com.ld.poetry.vo.upload.FileSizeUnitEnums;
import com.ld.poetry.vo.upload.LocalUploadInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@Service(CommonConst.UPLOAD_TYPE_KEY_LOCAL)
public class FileUploadLocalServiceImpl implements FileUploadService {
    @Override
    public String upload(MultipartFile file, ResourceConfig config, String key) throws IOException {
        // 默认配置
        LocalUploadInfo localUploadInfo = new LocalUploadInfo();

        // 如果有单独配置，使用单独配置
        if(StringUtils.isNotEmpty(config.getInfo())){
            localUploadInfo = JSON.parseObject(config.getInfo(), LocalUploadInfo.class);
        }

        // 单独配置存在问题，使用默认配置
        if(Objects.isNull(localUploadInfo) || StringUtils.isBlank(localUploadInfo.getUploadPath())){
            log.warn("配置暂未设置资源存放路径，使用默认存放路径.");
            localUploadInfo.setUploadPath(DEFAULT_UPLOAD_PATH);
        }

        // 根据单位获取文件实际大小，上传文件到指定目录，得到文件路径
        Long maxSizeLong = FileSizeUnitEnums.getMaxSizeLong(localUploadInfo.getUnit(), localUploadInfo.getMaxSize());
        String filePathEnd = FileUploadUtils.upload(localUploadInfo.getUploadPath(), file, maxSizeLong);

        // 获取访问资源的路径前缀,没有配置的话就获取当前请求的域名+端口
        String downloadUrl = config.getDownloadUrl();
        if(StringUtils.isBlank(config.getDownloadUrl())){
            HttpServletRequest request = PoetryUtil.getRequest();
            StringBuffer url = request.getRequestURL();
            log.info("upload:url={}",url);
            String uri = request.getRequestURI();
            log.info("upload:uri={}",uri);
            // 获取请求URL中的域名和端口
            downloadUrl = url.substring(0, url.indexOf(uri));
            log.info("upload:downloadUrl={}",downloadUrl);
        }

        // 返回可以直接访问文件的全路径
        return downloadUrl + "/" + filePathEnd;
    }
}
